gh-145217: Add colour to pprint output#145218
Conversation
This comment was marked as resolved.
This comment was marked as resolved.
This comment was marked as resolved.
This comment was marked as resolved.
This comment was marked as resolved.
This comment was marked as resolved.
| self._expand = bool(expand) | ||
| self._sort_dicts = sort_dicts | ||
| self._underscore_numbers = underscore_numbers | ||
| self._color = color |
There was a problem hiding this comment.
Shall we add a bool(color) conversion just as a few lines above?
self._compact = bool(compact)
self._expand = bool(expand)There was a problem hiding this comment.
Sure, can do, but not sure if it's necessary?
There was a problem hiding this comment.
Do we have explicit test for color=True and can_colorize=False? It's an end to end test.
something like
obj = {"key": "value"}
stream = io.StringIO()
# color=True should not produce no ANSI codes for streams
# that do not support color
pprint.pprint(obj, stream=stream, color=True)
result = stream.getvalue()
self.assertNotIn("\x1b[", result)Co-authored-by: sunmy2019 <59365878+sunmy2019@users.noreply.github.com>
Co-authored-by: sunmy2019 <59365878+sunmy2019@users.noreply.github.com>
Documentation build overview
6 files changed ·
|
I agree with this. But thinking further, our current highlighting logic relies on So, instead of special-casing Probe the text with tokenize first, No blacklist needed, no half-highlighted output. What do you think? def _colorize_output(text):
"""Apply syntax highlighting."""
- if "\x1b[" in text:
- # If the text already contains ANSI escape sequences
- # (for example, from a custom __repr__),
- # return as-is to avoid breaking their color.
+ # Probe: if the text cannot be fully tokenized, fall back to plain text
+ # to avoid the "half-highlighted" problem.
+ try:
+ list(tokenize.generate_tokens(_StringIO(text).readline))
+ except (SyntaxError, tokenize.TokenError):
return text
colors = list(gen_colors(text))
chars, _ = disp_str(text, colors=colors, force_color=True, escape=False)
|
Example:
pprintoutput #145217📚 Documentation preview 📚: https://cpython-previews--145218.org.readthedocs.build/